<template>
  <div>
    <mu-appbar title="">
      <mu-icon-button icon="navigate_before" slot="left" @click="$router.back()"/>
      <mu-flat-button label="发送" slot="right" @click="_confirmSubmit" :disabled="isSubmiting"/>
    </mu-appbar>
    <mu-card>
      <mu-content-block>
        <mu-text-field hintText="输入标题" v-model="title"/>
        <mu-text-field hintText="正文内容" multiLine :rows="5" v-model="content"/>
        <picture-picker/>
      </mu-content-block>
    </mu-card>
    <mu-toast v-if="showToast" :message="toastMessage" @close="showToast=false"/>
    <mu-dialog :open="showConfirmDialog" title="确定发送">
      是否确定发送
      <mu-flat-button label="返回" slot="actions" primary @click="showConfirmDialog=false"/>
      <mu-flat-button label="确定" slot="actions" primary @click="submit"/>
    </mu-dialog>
  </div>
</template>
<script>
  import PicturePicker from './ReportCourseFeedbackPicturePicker.vue'
  import resources from "../store/resources";
  import store from '../store/store'

  export default {
    components: {
      PicturePicker
    },
    data() {
      return {
        title: store.state.feedbackTitle,
        content: store.state.feedbackContent,

        isSubmiting: false,

        showToast: false,
        toastMessage: '',

        // showDialog: false
        showConfirmDialog:false
      }
    },
    props: {},
    computed:{
      selectedImage:()=>store.state.imageToUpload
    },
    methods: {
      submit() {

//        表单有效性验证
        if (!this._checkValidity()){
          this._reportValidity()
          return
        }

        this.isSubmiting = true
//        上传图片
        let uploadImagePromise = uploadImageList(this.selectedImage.map(value => value.image))
        uploadImagePromise
          .then(
            imageIdList => {
              return resources.createCourseFeedback({
                imageIds: imageIdList.join(','),
                title: this.title,
                content: this.content
              })
            },
            error => {
              throw error
            }
          )
          .then(
            () => {
//              创建成功
              this.isSubmiting = false
//              显示对话框
              this.showConfirmDialog = false
              this._routerBack()
              this.title = ''
              this.content = ''
              store.commit('initializeFeedback')
              store.commit('showToast','反馈成功')
            },
            () => {
//              创建失败
              this.showConfirmDialog  = false
              this.isSubmiting = false
              this._showToast('反馈失败')
            }
          )
      },
      _showToast(message) {
        this.showToast = true
        this.toastMessage = message
      },
      _routerBack() {
        console.log('back')
        this.$router.back()
      },
      _checkValidity(){
        if (this.title.trim().length === 0||this.content.trim().length===0){
          return false
        }
        return true
      },
      _reportValidity(){
        if (this.title.trim().length === 0){
          this._showToast('标题不能为空')
          return
        }
        if (this.content.trim().length === 0){
          this._showToast('内容不能为空')
          return
        }

      },
      _confirmSubmit(){
        this.showConfirmDialog = true
      }
    },
    beforeRouteLeave(to,from,next){
      store.commit('updateFeedbackTitle',this.title)
      store.commit('updateFeedbackContent',this.content)
      next()
    }
  }

  function uploadImageList(imageList) {
    let compressImageListPromise = Promise.all(imageList.map(compressImage))
    return compressImageListPromise.then(
      compressedImageList => Promise.all(compressedImageList.map(image => resources.uploadImage(image)))
    )
  }

  function compressImage(file) {
    return new Promise((resolve, reject) => {
      let cvs = document.createElement('canvas'),
        ctx = cvs.getContext('2d')
      const maxH = 200
      let img = new Image()
      img.src = URL.createObjectURL(file)
      img.onload = () => {
        if (img.height > maxH) {
          img.width *= maxH / img.height;
          img.height = maxH;
        }
        cvs.width = img.width;
        cvs.height = img.height;
        ctx.clearRect(0, 0, cvs.width, cvs.height);
        ctx.drawImage(img, 0, 0, img.width, img.height);
        cvs.toBlob(blob=>resolve(blobToFile(blob,file.name)), 'image/jpeg')
      }
    })
  }
  function blobToFile(theBlob, fileName){
    return new File([theBlob],fileName);
  }

</script>
<style scoped="">
	.mu-content-block{
 		padding: 8px 16px!important;
 }
</style>
